#! /usr/bin/env bash

_output="./git_version.h"


### GIT INFO ###

# check git command exist
if command -v git > /dev/null; then
    # check git repo exits
    if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
        # get commit id
        _commit=$(git rev-parse --short=12 HEAD 2> /dev/null)
        if [[ -z ${_commit} ]]; then
            _commit="-"
        fi
        # get branch name
        _branch="$(git symbolic-ref --short HEAD 2> /dev/null)"
        if [[ -z ${_branch} ]]; then
            _branch="<branch>"
        fi
        # get status clean/dirty
        _status=$(git status --porcelain)
        if [[ -z ${_status} ]]; then
		_status="" # clean (default)
        else
            _status="*" # dirty
        fi
    fi
fi


### BUILT TIME ###
_built=$(date +"%y%m%d%H%M%S")


### GIT VERSION ###
# _git_version="branch\\t${_branch}\\nstatus\\t${_status}\\ncommit\\t${_commit}\\nbuilt\\t${_built}"
_git_version="${_built} ${_commit}${_status}"


### SAVE HEADER FILE ###

_text=""
_text+="#ifndef _GIT_VERSION_H_\n"
_text+="#define _GIT_VERSION_H_\n"
_text+="\n"
_text+="#define GIT_VERSION \"${_git_version}\"\n"
_text+="\n"
_text+="#endif"

echo -e "${_text}" > ${_output}
